package com.yss.system.service.impl;

import java.util.*;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.validation.Validator;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yss.common.core.enums.YssStatusEnum;
import com.yss.common.core.utils.uuid.IdUtils;
import com.yss.common.datascope.annotation.DataScope;
import com.yss.system.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import com.yss.common.core.constant.UserConstants;
import com.yss.common.core.exception.BusinessException;
import com.yss.common.core.utils.StringUtils;
import com.yss.common.core.utils.bean.BeanValidators;
import com.yss.common.security.utils.SecurityUtils;
import com.yss.system.api.domain.SysRole;
import com.yss.system.api.domain.SysUser;
import com.yss.system.domain.SysPost;
import com.yss.system.domain.SysUserPost;
import com.yss.system.domain.SysUserRole;
import com.yss.system.mapper.SysPostMapper;
import com.yss.system.mapper.SysUserMapper;

/**
 * 用户 业务层处理
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {
    private static final Logger log = LoggerFactory.getLogger(SysUserServiceImpl.class);
    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private SysPostMapper postMapper;

    @Autowired
    private ISysUserRoleService userRoleService;

    @Autowired
    private ISysUserPostService userPostService;

    @Autowired
    private ISysConfigService configService;
    @Resource
    protected Validator validator;

    /**
     * 根据条件分页查询用户列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    @DataScope
    public List<SysUser> selectUserList(SysUser user) {
        QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
        if (null == user) {
            return userMapper.selectUserList(wrapper);
        }
        if (StringUtils.isNotEmpty(user.getUserName())) {
            wrapper.like("u.USER_NAME" , user.getUserName());
        }
        if (StringUtils.isNotEmpty(user.getId())) {
            wrapper.like("u.ID" , user.getId());
        }
        if (StringUtils.isNotEmpty(user.getPhonenumber())) {
            wrapper.like("u.PHONENUMBER" , user.getPhonenumber());
        }
        if (null != user.getStatus()) {
            wrapper.eq("u.STATUS" , user.getStatus());
        }
        if (StringUtils.isNotEmpty(user.getParams())) {
            if (null != user.getParams().get("beginTime" ) && StringUtils.isNotEmpty(user.getParams().get("beginTime" ).toString())) {
                wrapper.ge("u.CREATE_TIME" , user.getParams().get("beginTime" ));
            }
            if (null != user.getParams().get("endTime" ) && StringUtils.isNotEmpty(user.getParams().get("endTime" ).toString())) {
                wrapper.le("u.CREATE_TIME" , user.getParams().get("endTime" ));
            }
        }
        if (StringUtils.isNotEmpty(user.getDeptId())) {
            wrapper.eq("u.DEPT_ID" , user.getDeptId());
        } else {
            Object object = user.getParams().get("dataScope" );
            if (StringUtils.isNotNull(object)) {
                List<String> deptIds = (List<String>) object;
                if (StringUtils.isNotEmpty(deptIds)) {
                    wrapper.in("u.DEPT_ID" , deptIds);
                }
            }
        }
        return userMapper.selectUserList(wrapper);
    }

    /**
     * 根据条件分页查询已分配用户角色列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    @DataScope
    public List<SysUser> selectAllocatedList(SysUser user) {
        QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
        if (null == user || StringUtils.isEmpty(user.getRoleId())) {
            return null;
        }
        if (StringUtils.isNotEmpty(user.getUserName())) {
            wrapper.like("u.USER_NAME" , user.getUserName());
        }
        if (StringUtils.isNotEmpty(user.getPhonenumber())) {
            wrapper.like("u.PHONENUMBER" , user.getPhonenumber());
        }
        wrapper.eq("r.ID" , user.getRoleId());
        Object object = user.getParams().get("dataScope" );
        if (StringUtils.isNotNull(object)) {
            List<String> deptIds = (List<String>) object;
            if (StringUtils.isNotEmpty(deptIds)) {
                wrapper.in("d.ID" , deptIds);
            }
        }
        return userMapper.selectAllocatedList(wrapper);
    }

    /**
     * 根据条件分页查询未分配用户角色列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    @DataScope
    public List<SysUser> selectUnallocatedList(SysUser user) {
        QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
        if (null == user || StringUtils.isEmpty(user.getRoleId())) {
            return null;
        }
        if (StringUtils.isNotEmpty(user.getUserName())) {
            wrapper.like("u.USER_NAME" , user.getUserName());
        }
        if (StringUtils.isNotEmpty(user.getPhonenumber())) {
            wrapper.like("u.PHONENUMBER" , user.getPhonenumber());
        }
        wrapper.and(wreappper -> wreappper.ne("r.ID" , user.getRoleId()).or().isNull("r.ID" ));
        Object object = user.getParams().get("dataScope" );
        if (StringUtils.isNotNull(object)) {
            List<String> deptIds = (List<String>) object;
            if (StringUtils.isNotEmpty(deptIds)) {
                wrapper.in("d.ID" , deptIds);
            }
        }
        // 查询已经关联了该角色的用户 排除
        List<String> list = userMapper.selectAllocatedUserList(user);
        if (StringUtils.isNotEmpty(list)) {
            wrapper.notIn("u.ID" , list);
        }
        return userMapper.selectUnallocatedList(wrapper);
    }

    /**
     * 通过用户名查询用户
     *
     * @param userName 用户名
     * @return 用户对象信息
     */
    @Override
    public SysUser selectUserByUserName(String userName) {
        QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
        wrapper.eq("u.USER_NAME" , userName);
        List<SysUser> list = userMapper.selectUserList(wrapper);
        if (CollectionUtils.isEmpty(list)) {
            return null;
        }
        return list.get(0);
    }

    /**
     * 通过用户ID查询用户
     *
     * @param id 用户ID
     * @return 用户对象信息
     */
    @Override
    public SysUser selectUserById(String id) {
        QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
        wrapper.eq("u.ID" , id);
        List<SysUser> list = userMapper.selectUserList(wrapper);
        if (CollectionUtils.isEmpty(list)) {
            return null;
        }
        return list.get(0);
    }

    /**
     * 查询用户所属角色组
     *
     * @param userName 用户名
     * @return 结果
     */
    @Override
    public String selectUserRoleGroup(String userName) {
        QueryWrapper<SysRole> wrapper = new QueryWrapper<>();
        wrapper.eq("u.USER_NAME" , userName);
        List<SysRole> list = roleService.selectRoleList(wrapper);
        if (CollectionUtils.isEmpty(list)) {
            return StringUtils.EMPTY;
        }
        return list.stream().map(SysRole::getRoleName).collect(Collectors.joining("," ));
    }

    /**
     * 查询用户所属岗位组
     *
     * @param userName 用户名
     * @return 结果
     */
    @Override
    public String selectUserPostGroup(String userName) {
        List<SysPost> list = postMapper.selectPostsByUserName(userName);
        if (CollectionUtils.isEmpty(list)) {
            return StringUtils.EMPTY;
        }
        return list.stream().map(SysPost::getPostName).collect(Collectors.joining("," ));
    }

    /**
     * 校验用户名称是否唯一
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public boolean checkUserNameUnique(SysUser user) {
        String userId = StringUtils.isNull(user.getId()) ? "-1" : user.getId();
        QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
        wrapper.eq("USER_NAME" , user.getUserName());
        SysUser info = this.getOne(wrapper);
        if (StringUtils.isNotNull(info) && !info.getId().equals(userId)) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验手机号码是否唯一
     *
     * @param user 用户信息
     * @return
     */
    @Override
    public boolean checkPhoneUnique(SysUser user) {
        String userId = StringUtils.isNull(user.getId()) ? "-1" : user.getId();
        QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
        wrapper.eq("PHONENUMBER" , user.getPhonenumber());
        SysUser info = this.getOne(wrapper);
        if (StringUtils.isNotNull(info) && !info.getId().equals(userId)) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验email是否唯一
     *
     * @param user 用户信息
     * @return
     */
    @Override
    public boolean checkEmailUnique(SysUser user) {
        String userId = StringUtils.isNull(user.getId()) ? "-1" : user.getId();
        QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
        wrapper.eq("EMAIL" , user.getEmail());
        SysUser info = this.getOne(wrapper);
        if (StringUtils.isNotNull(info) && !info.getId().equals(userId)) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验用户是否允许操作
     *
     * @param user 用户信息
     */
    @Override
    public void checkUserAllowed(SysUser user) {
        if (StringUtils.isNotNull(user.getId()) && user.isAdmin()) {
            throw new BusinessException("不允许操作超级管理员用户" );
        }
    }

    /**
     * 校验用户是否有数据权限
     *
     * @param userId 用户id
     */
    @Override
    public void checkUserDataScope(String userId) {
        if (SysUser.isAdmin(SecurityUtils.getUserId())) {
            return;
        }
        SysUser user = new SysUser();
        user.setId(userId);
        List<SysUser> users = this.selectUserList(user);
        if (StringUtils.isEmpty(users)) {
            throw new BusinessException("没有权限访问用户数据！" );
        }

    }

    /**
     * 新增保存用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertUser(SysUser user) {
        user.setStatus(YssStatusEnum.NORMAL.getCode());
        user.setCreateTime(new Date());
        user.setCreateBy(SecurityUtils.getUsername());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        user.setId(IdUtils.fastSimpleUUID());
        // 新增用户信息
        int rows = userMapper.insert(user);
        // 新增用户岗位关联
        this.insertUserPost(user);
        // 新增用户与角色管理
        this.insertUserRole(user);
        return rows;
    }

    /**
     * 注册用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public boolean registerUser(SysUser user) {
        return userMapper.insert(user) > 0;
    }

    /**
     * 修改保存用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateUser(SysUser user) {
        user.setUpdateBy(SecurityUtils.getUsername());
        user.setUpdateTime(new Date());
        String userId = user.getId();
        // 删除用户与角色关联
        QueryWrapper<SysUserRole> wrapper = new QueryWrapper<>();
        wrapper.eq("USER_ID" , userId);
        userRoleService.remove(wrapper);
        // 新增用户与角色管理
        this.insertUserRole(user);
        // 删除用户与岗位关联
        QueryWrapper<SysUserPost> wrapperUserPost = new QueryWrapper<>();
        wrapperUserPost.eq("USER_ID" , userId);
        userPostService.remove(wrapperUserPost);
        // 新增用户与岗位管理
        this.insertUserPost(user);
        return userMapper.updateById(user);
    }

    /**
     * 用户授权角色
     *
     * @param userId  用户ID
     * @param roleIds 角色组
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void insertUserAuth(String userId, String[] roleIds) {
        QueryWrapper<SysUserRole> wrapper = new QueryWrapper<>();
        wrapper.eq("USER_ID" , userId);
        userRoleService.remove(wrapper);
        insertUserRole(userId, roleIds);
    }

    /**
     * 修改用户状态
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int updateUserStatus(SysUser user) {
        return userMapper.updateById(user);
    }

    /**
     * 修改用户基本信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int updateUserProfile(SysUser user) {
        return userMapper.updateById(user);
    }

    /**
     * 修改用户头像
     *
     * @param userName 用户名
     * @param avatar   头像地址
     * @return 结果
     */
    @Override
    public boolean updateUserAvatar(String userName, String avatar) {
        UpdateWrapper<SysUser> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("USER_NAME" , userName);
        SysUser sysUser = new SysUser();
        sysUser.setAvatar(avatar);
        return this.update(sysUser, updateWrapper);
    }

    /**
     * 重置用户密码
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int resetPwd(SysUser user) {
        return userMapper.updateById(user);
    }

    /**
     * 重置用户密码
     *
     * @param userName 用户名
     * @param password 密码
     * @return 结果
     */
    @Override
    public int resetUserPwd(String userName, String password) {
        UpdateWrapper<SysUser> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("USER_NAME" , userName);
        SysUser sysUser = new SysUser();
        sysUser.setPassword(password);
        return userMapper.update(sysUser, updateWrapper);
    }

    /**
     * 新增用户角色信息
     *
     * @param user 用户对象
     */
    public void insertUserRole(SysUser user) {
        this.insertUserRole(user.getId(), user.getRoleIds());
    }

    /**
     * 新增用户岗位信息
     *
     * @param user 用户对象
     */
    public void insertUserPost(SysUser user) {
        String[] posts = user.getPostIds();
        if (StringUtils.isEmpty(posts)) {
            return;
        }
        // 新增用户与岗位管理
        List<SysUserPost> list = new ArrayList<SysUserPost>();
        for (String postId : posts) {
            SysUserPost up = new SysUserPost();
            up.setId(IdUtils.fastSimpleUUID());
            up.setUserId(user.getId());
            up.setPostId(postId);
            list.add(up);
        }
        userPostService.saveBatch(list);

    }

    /**
     * 新增用户角色信息
     *
     * @param userId  用户ID
     * @param roleIds 角色组
     */
    public void insertUserRole(String userId, String[] roleIds) {
        if (StringUtils.isEmpty(roleIds)) {
            return;
        }
        // 新增用户与角色管理
        List<SysUserRole> list = new ArrayList<SysUserRole>();
        for (String roleId : roleIds) {
            SysUserRole ur = new SysUserRole();
            ur.setId(IdUtils.fastSimpleUUID());
            ur.setUserId(userId);
            ur.setRoleId(roleId);
            list.add(ur);
        }
        userRoleService.saveBatch(list);

    }

    /**
     * 通过用户ID删除用户
     *
     * @param userId 用户ID
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteUserById(String userId) {
        // 删除用户与角色关联
        QueryWrapper<SysUserRole> wrapper = new QueryWrapper<>();
        wrapper.eq("USER_ID" , userId);
        userRoleService.remove(wrapper);
        // 删除用户与岗位表
        QueryWrapper<SysUserPost> wrapperUserPost = new QueryWrapper<>();
        wrapperUserPost.eq("USER_ID" , userId);
        userPostService.remove(wrapperUserPost);
        return userMapper.deleteById(userId);
    }

    /**
     * 批量删除用户信息
     *
     * @param userIds 需要删除的用户ID
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteUserByIds(String[] userIds) {
        for (String userId : userIds) {
            SysUser user = new SysUser();
            user.setId(userId);
            this.checkUserAllowed(user);
            this.checkUserDataScope(userId);
        }
        List<String> list = Arrays.asList(userIds);
        // 删除用户与角色关联
        QueryWrapper<SysUserRole> wrapper = new QueryWrapper<>();
        wrapper.in("USER_ID" , list);
        userRoleService.remove(wrapper);
        // 删除用户与岗位关联
        QueryWrapper<SysUserPost> wrapperUserPost = new QueryWrapper<>();
        wrapperUserPost.in("USER_ID" , list);
        userPostService.remove(wrapperUserPost);
        return userMapper.deleteBatchIds(list);
    }

    /**
     * 导入用户数据
     *
     * @param userList        用户数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName        操作用户
     * @return 结果
     */
    @Override
    public String importUser(List<SysUser> userList, Boolean isUpdateSupport, String operName) {
        if (StringUtils.isNull(userList) || userList.size() == 0) {
            throw new BusinessException("导入用户数据不能为空！" );
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        String password = configService.selectConfigByKey("sys.user.initPassword" );
        for (SysUser user : userList) {
            try {
                // 验证是否存在这个用户
                SysUser u = this.selectUserByUserName(user.getUserName());
                if (StringUtils.isNull(u)) {
                    BeanValidators.validateWithException(validator, user);
                    user.setPassword(SecurityUtils.encryptPassword(password));
                    user.setCreateBy(operName);
                    this.insertUser(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 导入成功" );
                } else if (isUpdateSupport) {
                    BeanValidators.validateWithException(validator, user);
                    checkUserAllowed(user);
                    checkUserDataScope(user.getId());
                    user.setUpdateBy(operName);
                    this.updateUser(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 更新成功" );
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、账号 " + user.getUserName() + " 已存在" );
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、账号 " + user.getUserName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：" );
            throw new BusinessException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：" );
        }
        return successMsg.toString();
    }

}
